package com.epro.dx.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BrowseAcitivty;
import com.epro.dx.activity.FavoritesActivity;
import com.epro.dx.activity.FeedBackActivity;
import com.epro.dx.activity.HomeActivity;
import com.epro.dx.activity.LoginActivity;
import com.epro.dx.activity.SettingsActivity;
import com.epro.dx.activity.TrackSubscriptActivity;
import com.epro.dx.activity.chagepassword.ChangePasswordActivity;
import com.epro.dx.activity.coupon.CouponActivity;
import com.epro.dx.activity.myaddress.MyAddressBookActivity;
import com.epro.dx.activity.order.MyOrdersActivity;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.ClickUtils;
import com.epro.dx.util.DpPxUtils;
import com.epro.dx.widget.BottomBtn;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.OrderStatusModel;
import com.weipu.common.facade.model.UserModel;
import com.weipu.common.observer.RedDotObserver;
import com.weipu.common.subject.RedDotSubjectImpl;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;
import com.weipu.common.util.utils.SPUtils;

/**
 * 我的账户
 *
 * @author hjd008
 * @version [版本号, 2015-1-6]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@SuppressLint("InlinedApi")
public class MyAccountFragment extends BaseFragment implements OnClickListener, RedDotObserver {

    private View rootView;

    private Context mContext;

    private RelativeLayout myTikectLayout, myCouponLayout, myWishListLayout,
            myAddressBook, myFeedBacks, myBrowsedHistory, myChangePwd,
            mySettings;

    //新增功能 物流订阅入口
    private RelativeLayout myOrderTrackingLayout;

    //新功能小红点提示
    private ImageView redDotIv;

    private LinearLayout orderAll, orderPendingPayment, orderPendingDelivery,
            orderFullShipment;

    private TextView mUsername, mPonit, orderPendingPaymentNum,
            orderPendingDeliveryNum, orderFullShipmentNum;

    private Button logoutBtn;

    private ScrollView scrollView;

    private UserModel userModel;

    private OrderStatusModel orderStatus;

    private String username;

    private String userPoint;

    private String customerid = null;

    private boolean isNeedRefresh;

    private ImageView userPhoto;

    private String beenClickItem = null;

    private Handler userHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what != 0) {
                hideWaitingDialog();
            }
            if (null == userModel) {
                return;
            }
//			getUserPhoto();
            username = userModel.getUsername();
            double point = userModel.getPoints();
            if (point < 0) {//积分服务异常是返回的数值-32768
                mPonit.setVisibility(View.INVISIBLE);
            } else {
                mPonit.setVisibility(View.VISIBLE);
                userPoint = String.format("%.2f", userModel.getPoints());
                mPonit.setText(mContext.getResources().getString(
                        R.string.my_point_title, userPoint));
            }
            if ("".equals(username) || null == username) {
                username = StringUtil.getConfig(
                        getActivity(), ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
            }
            mUsername.setText(username);


        }

        ;
    };

    private Tracker tracker;

    private EventBuilder eventBuilder;
    private SPUtils spUtils;
    private boolean isKnowNewFun;

    @Override
    public void onAttach(Activity activity) {
        mContext = activity;
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        tracker = ((DXApplication) getActivity().getApplication()).getTracker(TrackerName.APP_TRACKER);
        eventBuilder = new HitBuilders.EventBuilder();
        if (null == rootView) {
            rootView = inflate(R.layout.fragment_settings);
//			setTitleContent(R.string.title_my_Account);
            initView();
            initData();
            setListenner();

        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        //注册小红点观察者
        RedDotSubjectImpl.getInstance().registerObserver(this);
        return rootView;
    }


    private void checkLoginAndResetUI() {
        if (ActivityUtil.isLogin(mContext)) {
//			mPonit.setVisibility(View.VISIBLE);
            mUsername.setVisibility(View.VISIBLE);
//			logoutBtn.setText("LOGOUT");
            logoutBtn.setVisibility(View.GONE);
        } else {
//			mPonit.setVisibility(View.INVISIBLE);
            mPonit.setText(mContext.getResources().getString(
                    R.string.my_point_title, "0.00"));
            mUsername.setVisibility(View.INVISIBLE);
            logoutBtn.setVisibility(View.VISIBLE);
            logoutBtn.setText("LOGIN");
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
//			if(null==customerid||"0".equals(customerid)){
//				AsyncTaskUtil.executeTask(new LoadingUserInfo(false));
//			}else{
            if (ActivityUtil.isLogin(mContext)) {
                AsyncTaskUtil.executeTask(new LoadingUserInfo(true));
            }
//			}
            checkLoginAndResetUI();
        } else {
            if (null != scrollView) {
                scrollView.fullScroll(ScrollView.FOCUS_UP);
            }
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onResume() {
        if (isNeedRefresh) {
            if (ActivityUtil.isLogin(mContext)) {
                AsyncTaskUtil.executeTask(new LoadingUserInfo(true));
            }
        }
        checkLoginAndResetUI();
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void initView() {
        scrollView = (ScrollView) rootView.findViewById(R.id.scroll_view);
        userPhoto = (ImageView) rootView.findViewById(R.id.my_phote_iv);
        logoutBtn = (Button) rootView.findViewById(R.id.logout_btn);
        orderAll = (LinearLayout) rootView.findViewById(R.id.order_all);
        orderPendingPayment = (LinearLayout) rootView
                .findViewById(R.id.order_pending_payment);
        orderPendingDelivery = (LinearLayout) rootView
                .findViewById(R.id.order_pending_delivery);
        orderFullShipment = (LinearLayout) rootView
                .findViewById(R.id.order_full_shipment);
        mUsername = (TextView) rootView.findViewById(R.id.my_username);
        mPonit = (TextView) rootView.findViewById(R.id.my_point);
        if ("".equals(username) || null == username) {
            username = StringUtil.getConfig(
                    getActivity(), ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
        }
        mUsername.setText(username);
        mPonit.setText(mContext.getResources().getString(
                R.string.my_point_title, "0.00"));
        // myTikectLayout = (RelativeLayout) rootView
        // .findViewById(R.id.myaccount_my_tickets_layout);
        myCouponLayout = (RelativeLayout) rootView
                .findViewById(R.id.myaccount_my_coupon_layout);
        myWishListLayout = (RelativeLayout) rootView
                .findViewById(R.id.my_account_wishlist_layout);
        myAddressBook = (RelativeLayout) rootView
                .findViewById(R.id.my_address_book_layout);
        myFeedBacks = (RelativeLayout) rootView
                .findViewById(R.id.my_account_feedback_layout);
        myBrowsedHistory = (RelativeLayout) rootView
                .findViewById(R.id.my_account_browsed_layout);
        myChangePwd = (RelativeLayout) rootView
                .findViewById(R.id.my_account_change_password_layout);
        mySettings = (RelativeLayout) rootView
                .findViewById(R.id.my_account_settings);

        //新增功能 物流订阅入口
        myOrderTrackingLayout = (RelativeLayout)
                rootView.findViewById(R.id.my_account_order_tracking_layout);

        orderPendingPaymentNum = (TextView) rootView
                .findViewById(R.id.pending_payment_num);
        orderPendingDeliveryNum = (TextView) rootView
                .findViewById(R.id.pending_delivery_num);
        orderFullShipmentNum = (TextView) rootView
                .findViewById(R.id.full_shipment_num);

        //物流订阅小红点
        redDotIv = (ImageView)
                rootView.findViewById(R.id.my_account_order_tracking_red_dot);

//		getCustormid();
    }

    private void initData() {
        spUtils = new SPUtils(getResources().getString(R.string.app_name_en));
        //是否已经阅读过新功能
        isKnowNewFun = spUtils.getBoolean(Constant.Global.IS_KONW_NEW_FUN, false);
        if (!isKnowNewFun) {
            redDotIv.setVisibility(View.VISIBLE);
        }
    }

    private void setListenner() {
        orderAll.setOnClickListener(this);
        logoutBtn.setOnClickListener(this);
        mySettings.setOnClickListener(this);
        myFeedBacks.setOnClickListener(this);
        myChangePwd.setOnClickListener(this);
        myAddressBook.setOnClickListener(this);
        myCouponLayout.setOnClickListener(this);
        myWishListLayout.setOnClickListener(this);
        myBrowsedHistory.setOnClickListener(this);
        orderFullShipment.setOnClickListener(this);
        orderPendingPayment.setOnClickListener(this);
        orderPendingDelivery.setOnClickListener(this);
        myOrderTrackingLayout.setOnClickListener(this);
    }

    /**
     * 获取用户id
     */
    private void getCustormid() {
        customerid = GlobalConfig.getInstance().getUserSessionCfg()
                .getCustomerid();
        if (null == customerid || "".equals(customerid)) {
            customerid = StringUtil.getConfig(
                    ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, "0");
        }
    }

    @Override
    public void noticeHasRead() {
        redDotIv.setVisibility(View.GONE);
        //同时保存已读的状态
        spUtils.put(Constant.Global.IS_KONW_NEW_FUN,true);
    }

    /**
     * 进入页面加载用户数据
     *
     * @author hf
     */

    protected class LoadingUserInfo extends BaseNeedReLoginTask {
        //        private boolean isLogin;
        private boolean isLoadUserInfo;

        public LoadingUserInfo(boolean isLoadUserInfo) {
            this.isLoadUserInfo = isLoadUserInfo;
        }

        @Override
        protected void onPreExecute() {
//			if(!isLogin){
//				showWaitingDialog();
//			}
        }

        @Override
        protected String doInBackground(Void... params) {

            try {
//				if ("0".equals(customerid) || null == customerid
//						|| "".equals(customerid)) {
                getCustormid();
//				}
                if (isLoadUserInfo) {
                    userModel = ProviderFactory.createUserServiceProvider()
                            .getAccountForUser(customerid, ActivityUtil.getCustomerToken());
                    if (userModel != null) {
                        userHandler.sendEmptyMessage(0);
                    }
                }
                //屏蔽小红点的显示
//				orderStatus = ProviderFactory.createOrderServiceProvider()
//						.getOrderCount(Long.parseLong(customerid));

            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("MyAccountFragment", "LoadingUserInfo", e);
            }

            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            mPonit.setVisibility(View.VISIBLE);
            hideWaitingDialog();
            if ("0".equals(result)) {
                if (null != orderStatus) {
                    setOrderStatusNum(orderStatus
                            .getPendingPayment(), orderPendingPaymentNum);
                    setOrderStatusNum(orderStatus
                            .getPendingDelivery(), orderPendingDeliveryNum);
                    setOrderStatusNum(orderStatus
                            .getFullShipment(), orderFullShipmentNum);
                }
            } else if (!isRelogin) {
                AlertToast.alert(mContext,
                        ServerConstant.ReturnCode.MESSAGEMAP.get(result));
            }
        }

        @Override
        protected Context setContext() {
            return getActivity();
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new LoadingUserInfo(isLoadUserInfo);
        }
    }

    private void setOrderStatusNum(int num, TextView view) {
        String showNum = "";
        if (num <= 0) {
            view.setVisibility(View.INVISIBLE);
        } else {

            if (num > 99) {
                showNum = "99+";
            } else {
                showNum = num + "";
            }
            view.setVisibility(View.VISIBLE);
            if (showNum.length() > 2) {
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        DpPxUtils.Dp2Px(getActivity(), 25),
                        DpPxUtils.Dp2Px(getActivity(), 25));
                layoutParams.topMargin = DpPxUtils.Dp2Px(getActivity(), -17);
                view.setLayoutParams(layoutParams);
            }
            view.setText(showNum);
        }

    }

    /**
     * 跳转登录界面
     *
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void gotoLogin() {
        ((HomeActivity) getActivity()).currentTab = BottomBtn.ACCOUNT_TAG;
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        Bundle data = new Bundle();
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_MYACCOUNT);
        data.putString(HomeActivity.CURRENT_TAB_TAG, BottomBtn.ACCOUNT_TAG);
        data.putString(ServerConstant.Parameter.PARAMETER_FROMACOUNTCLICK, beenClickItem);
        intent.putExtras(data);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if (ClickUtils.isFastDoubleClick()) {
            return;
        }
        Intent intent = new Intent();
        switch (v.getId()) {
            // case R.id.myaccount_my_tickets_layout:
            // return;
            case R.id.myaccount_my_coupon_layout:
                isNeedRefresh = true;
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "myCoupon";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check MyCoupon");
                tracker.send(eventBuilder.build());
                intent.setClass(getActivity(), CouponActivity.class);
                intent.putExtra("pageNumber", 1);
                break;
            case R.id.my_account_wishlist_layout:
                isNeedRefresh = true;
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "myWishList";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check wishlist");
                tracker.send(eventBuilder.build());
                intent.setClass(getActivity(), FavoritesActivity.class);
                break;
            case R.id.my_address_book_layout:
                isNeedRefresh = true;
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "myAddressBook";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check address book");
                tracker.send(eventBuilder.build());
                intent.putExtra("fromChooseAdd", false);
                intent.setClass(getActivity(), MyAddressBookActivity.class);
                break;
            case R.id.my_account_feedback_layout:
                eventBuilder.setCategory("Click").setAction("Go to feedback");
                tracker.send(eventBuilder.build());
                intent.setClass(getActivity(), FeedBackActivity.class);
                break;
            case R.id.my_account_browsed_layout:
                isNeedRefresh = true;
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "browsed";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check browsed history");
                tracker.send(eventBuilder.build());
                intent.setClass(getActivity(), BrowseAcitivty.class);
                break;
            case R.id.my_account_change_password_layout:
                isNeedRefresh = true;
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "changePassword";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Change password");
                tracker.send(eventBuilder.build());
                intent.setClass(getActivity(), ChangePasswordActivity.class);
                break;
            case R.id.my_account_settings:
                eventBuilder.setCategory("Click").setAction("Go to settings");
                tracker.send(eventBuilder.build());
                intent.setClass(getActivity(), SettingsActivity.class);
                break;

            case R.id.order_all:
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "orderAll";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check order_all");
                tracker.send(eventBuilder.build());
                intent.putExtra("fragmentIndex", 0);
                intent.setClass(getActivity(), MyOrdersActivity.class);
                isNeedRefresh = true;
                break;
            case R.id.order_pending_payment:
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "orderPendingPayment";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check order_pending_payment");
                tracker.send(eventBuilder.build());
                intent.putExtra("fragmentIndex", 1);
                intent.setClass(getActivity(), MyOrdersActivity.class);
                isNeedRefresh = true;
                break;
            case R.id.order_pending_delivery:
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "orderPendingDelivery";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check order_pending_delivery");
                tracker.send(eventBuilder.build());
                intent.putExtra("fragmentIndex", 2);
                intent.setClass(getActivity(), MyOrdersActivity.class);
                isNeedRefresh = true;
                break;
            case R.id.order_full_shipment:
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "orderFullShipment";
                    gotoLogin();
                    return;
                }
                eventBuilder.setCategory("Click").setAction("Check order_full_shipment");
                tracker.send(eventBuilder.build());
                intent.putExtra("fragmentIndex", 3);
                intent.setClass(getActivity(), MyOrdersActivity.class);
                isNeedRefresh = true;
                break;
            case R.id.logout_btn:
                eventBuilder.setCategory("Click").setAction("Login");
                tracker.send(eventBuilder.build());
                //没有登陆，去登陆
                isNeedRefresh = true;
                beenClickItem = "";
                gotoLogin();
                return;

            //物流订阅入口点击事件
            case R.id.my_account_order_tracking_layout:
                //判断是否登录，如果未登录，先跳转到登录界面
                if (!ActivityUtil.isLogin(mContext)) {
                    beenClickItem = "orderTrack";
                    gotoLogin();
                    return;
                } else {
                    //在这里通知新功能已读，保存已读的状态,不过只有在新功能还未读的情况下才通知观察者
                    if (!isKnowNewFun) {
                        RedDotSubjectImpl.getInstance().notifyObserver();
                    }
                }
                eventBuilder.setCategory("Click").setAction("Check order_tracking");
                tracker.send(eventBuilder.build());
                intent.setClass(getActivity(), TrackSubscriptActivity.class);
                isNeedRefresh = true;

                break;

            default:
                break;
        }
        if (R.id.logout_btn != v.getId()) {
            startActivity(intent);
        }

    }

    private void logoutResetValue() {
        mUsername.setText("");
        username = "";
        userPoint = "";
        mPonit.setText(mContext.getResources().getString(
                R.string.my_point_title, "0.00"));
        customerid = "";
        scrollView.fullScroll(ScrollView.FOCUS_UP);
        orderPendingPaymentNum.setVisibility(View.INVISIBLE);
        orderPendingDeliveryNum.setVisibility(View.INVISIBLE);
        orderFullShipmentNum.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RedDotSubjectImpl.getInstance().unRegisterObserver(this);
    }
}
